package com.zidongxiangxi.clock.server.repository;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zidongxiangxi.clock.server.repository.entity.Clock;
import com.zidongxiangxi.clock.server.repository.mapper.ClockMapper;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;

/**
 * @author chenxudong
 * @date 2020/07/22
 */
@Repository
public class ClockDao extends ServiceImpl<ClockMapper, Clock> {
    public List<Clock> loadAlarmClock(int maxTaskNum, Long minNextTryTime) {
        QueryWrapper<Clock> queryWrapper = new QueryWrapper<>();
        queryWrapper
            .lt(Clock.NEXT_TRY_TIME, minNextTryTime)
            .last("limit 0," + maxTaskNum);
        return baseMapper.selectList(queryWrapper);
    }

    public List<Clock> queryExpireClock() {
        QueryWrapper<Clock> queryWrapper = new QueryWrapper<>();
        queryWrapper.lt(Clock.NEXT_TRY_TIME, System.currentTimeMillis());
        return baseMapper.selectList(queryWrapper);
    }

    public Clock getAlarmClockByApplicationAndBusinessId(String application, String businessId) {
        QueryWrapper<Clock> queryWrapper = new QueryWrapper<>();
        queryWrapper
            .eq(Clock.APPLICATION, application)
            .eq(Clock.BUSINESS_ID, businessId);
        List<Clock> alarmClocks = baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(alarmClocks)) {
            return null;
        }
        return alarmClocks.get(0);
    }

    public void changeNextTryTime(Long id, Long newNextTryTime) {
        changeNextTryTime(Collections.singletonList(id), newNextTryTime);
    }

    public void changeNextTryTime(List<Long> ids, Long newNextTryTime) {
        baseMapper.changeNextTryTime(ids, newNextTryTime);
    }

}
